package com.spring.sunflower.userinfo;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.spring.sunflower.R;
import com.spring.sunflower.base.BaseActivity;
import com.spring.sunflower.bean.PhotoListBean;
import com.spring.sunflower.bean.PhotoListReleaseBean;
import com.spring.sunflower.bean.STSCertBean;
import com.spring.sunflower.common.CommonContract;
import com.spring.sunflower.common.FileUploadCallback;
import com.spring.sunflower.common.PhotoViewerActivity;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.util.AliUploadUtils;
import com.spring.sunflower.util.PathUtils;

import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Kevin on 2021/7/1<br/>
 * <p>
 * Describe:<br/>
 */
public class PhotoWallActivity extends BaseActivity<PhotoWallPresenter> implements CommonContract.PhotoWallView {
    private RecyclerView recyclerView;
    private String keyID;
    private String keySecret;
    private String securityToken;
    private List<PhotoListBean.DatasBean> mData = new ArrayList<>();
    private PhotoWallAdapter mAdapter;
    private AliUploadUtils aliUploadUtils;
    private boolean hasAddButton = false;

    @Override
    public void initView() {
        Intent intent = getIntent();
        keyID = intent.getStringExtra(Constant.ALI_KEY_ID);
        keySecret = intent.getStringExtra(Constant.ALI_KEY_SECRET);
        securityToken = intent.getStringExtra(Constant.ALI_SECURITY_TOKEN);
        if (TextUtils.isEmpty(keyID) || TextUtils.isEmpty(keySecret) || TextUtils.isEmpty(securityToken)) {
            mPresenter.getSTSCert();
        } else {
            aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken);
        }

        tvTitle.setText("照片墙");
        recyclerView = findViewById(R.id.rvRecyclerView);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        recyclerView.setLayoutManager(gridLayoutManager);

        mAdapter = new PhotoWallAdapter(R.layout.adapter_item_photo_list, mData);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                PhotoListBean.DatasBean datasBean = mData.get(position);
                ArrayList<String> tempList = new ArrayList<>();
                for (PhotoListBean.DatasBean data : mData) {
                    if (!data.isPlaceHolder()) {
                        tempList.add(data.getPhotoPath());
                    }
                }
                if (datasBean.isPlaceHolder()) {
                    //上传照片
                    checkOpenGallery(PhotoWallActivity.this, true);
//                    PictureSelector.create(PhotoWallActivity.this)
//                            .openGallery(PictureMimeType.ofImage())
//                            .imageEngine(GlideEngine.createGlideEngine())/**/
//                            .isWeChatStyle(true)
//                            .maxSelectNum(8 - mData.size() + 1)
//                            .selectionMode(PictureConfig.MULTIPLE)
//                            .isCamera(true)
//                            .minimumCompressSize(100)
//                            .forResult(PictureConfig.CHOOSE_REQUEST);

                } else {
                    Intent intent = new Intent(PhotoWallActivity.this, PhotoViewerActivity.class);
                    intent.putStringArrayListExtra(Constant.PHOTO_LIST_VIEWER, tempList);
                    intent.putExtra(Constant.PHOTO_CURRENT_POSITION, position);
                    startActivity(intent);
                }
            }
        });
        mAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                List<PhotoListBean.DatasBean> data = new ArrayList<>();
                for (PhotoListBean.DatasBean bean : mData) {
                    bean.setShowDelete(true);
                    data.add(bean);
                }
                mAdapter.setNewInstance(data);
                return true;
            }
        });
        mAdapter.addChildClickViewIds(R.id.rivDelete);
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
//                showToast("mData.size=" + mData.size());
                PhotoListBean.DatasBean datasBean = mData.get(position);
                Map<String, String> map = new HashMap<>();
                map.put("id", datasBean.getId());
                mPresenter.deletePhoto(map, position);
            }
        });
        queryPhotoX();
    }

    private void queryPhotoX() {
        String userId = getField(Constant.KEY_USERID, "");
        Map<String, String> map = new HashMap<>();
        map.put("memberId", userId);
        map.put("pageIndex", "1");
        mPresenter.queryPhoto(map);
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_photo_wall;
    }

    @Override
    public PhotoWallPresenter setPresenter() {
        return new PhotoWallPresenter(this);
    }

    @Override
    public void updateSuccess(PhotoListReleaseBean.DatasBean bean) {
        hideLoading();
        PhotoListBean.DatasBean dataBean = new PhotoListBean.DatasBean();
        dataBean.setId(bean.getId());
        dataBean.setMemberId(bean.getMemberId());
        dataBean.setPhotoPath(bean.getPhotoPath());
        dataBean.setWidth(bean.getWidth());
        dataBean.setHeight(bean.getHeight());
        dataBean.setIsVerify(bean.getIsVerify());
        dataBean.setCreateTime(bean.getCreateTime());
        dataBean.setPlaceHolder(false);
        if (mData.size() == 8) {
            mAdapter.removeAt(7);
            mAdapter.addData(dataBean);
            hasAddButton = false;
        } else {
            mAdapter.addData(mData.size() - 1, dataBean);
        }

    }

    @Override
    public void updateFailed() {
        hideLoading();
    }

    @Override
    public void querySuccess(List<PhotoListBean.DatasBean> data) {
        Collections.reverse(data);
        mAdapter.addData(data);
        if (data.size() < 8) {
            PhotoListBean.DatasBean bean = new PhotoListBean.DatasBean();
            bean.setPlaceHolder(true);
            mAdapter.addData(bean);
            hasAddButton = true;
        } else {
        }
    }

    @Override
    public void queryFailed() {

    }

    @Override
    public void deleteSuccess(int position) {
        mAdapter.removeAt(position);
        mData.remove(position);
        List<PhotoListBean.DatasBean> data = new ArrayList<>();
        for (PhotoListBean.DatasBean bean : mAdapter.getData()) {
            bean.setShowDelete(false);
            data.add(bean);
        }
        mAdapter.setNewInstance(data);
        if (!hasAddButton) {
            PhotoListBean.DatasBean bean = new PhotoListBean.DatasBean();
            bean.setPlaceHolder(true);
            mAdapter.addData(bean);
            hasAddButton = true;
        }

    }

    @Override
    public void deleteFailed() {

    }

    @Override
    public void loadSTSCert(STSCertBean.DatasBean data) {
        keyID = data.getAccessKeyId();
        keySecret = data.getAccessKeySecret();
        securityToken = data.getSecurityToken();
        aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                if (data != null) {
                    List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : localMedia) {
                        showLoading();
                        String path = media.getPath();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            path = PathUtils.getPath(PhotoWallActivity.this, Uri.parse(path));
                        }
                        if (media.isCut()) {
                            path = media.getCutPath();
                        }
                        aliUploadUtils.upLoadFile(path, new FileUploadCallback() {
                            @Override
                            public void onFailure(String str) {
                                showToast(str);
                                hideLoading();
                            }

                            @Override
                            public void onSuccess(Object paramRequestString, String filePath) {
                                Map<String, String> map = new HashMap<>();
                                map.put("photoPath", filePath);
                                map.put("width", String.valueOf(media.getWidth()));
                                map.put("height", String.valueOf(media.getHeight()));
                                mPresenter.releasePhoto(map);
                            }

                            @Override
                            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                            }
                        });
                    }
                }
            }
        }
    }
//    @Override
//    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
//        switch (item.getItemId()) {
//            case android.R.id.home:
//
//                onBackPressed();
//                break;
//        }
//        return true;
//    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, UserInfoEditActivity.class);
        intent.putExtra(Constant.USER_PHOTO_LIST, (Serializable) mAdapter.getData());
        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }
}
